package com.sk.weichat.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.sk.weichat.R;
import com.sk.weichat.adapter.GroupMembersHeadAdapter;
import com.sk.weichat.bean.RoomMember;
import com.sk.weichat.sortlist.BaseSortModel;
import com.sk.weichat.view.ClearEditText;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class SearchUtils {
    private Activity mActivity;
    private View searchView;

    private ClearEditText ediSearch;
    private View alphaView;
    private TextView tvCancle;
    private PopupWindow popupWindow;
    private int moveHeight;
    private int statusBarHeight;
    private View fatherView;// 界面的跟布局
    private View topTitleView;// 标题栏布局
    private RecyclerView recy_search;
    private LinearLayout ll_empty;
    private onItemClickOListener listener;

    private GroupMembersHeadAdapter membersHeadAdapter;
    private List<BaseSortModel<RoomMember>> mSortHeadRoomMember;

    private List<BaseSortModel<RoomMember>> mSearchRoomMember = new ArrayList<>();


    /**
     *
     * @param activity
     * @param rlTopTitle
     *            ,标题栏布局
     * @param llFather
     *            ,界面的跟布局
     * @param
     *            ，文本框监听
     * @param strHint
     *            ,搜索框的提示语
     */
    public SearchUtils(Activity activity, View rlTopTitle, final View llFather,
                       String strHint, List<BaseSortModel<RoomMember>> mSortHeadRoomMember,onItemClickOListener listener) {
        super();
        this.mActivity = activity;
        this.topTitleView = rlTopTitle;
        this.fatherView = llFather;
        this.mSortHeadRoomMember = mSortHeadRoomMember;
        this.listener = listener;
        initViews(strHint);
        initListener();
    }

    private void initListener() {

        // TODO Auto-generated method stub
        alphaView.setOnClickListener(onClick);
        tvCancle.setOnClickListener(onClick);
        ediSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mSearchRoomMember.clear();
                String str = s.toString();
                if (TextUtils.isEmpty(str)) {
                    recy_search.setVisibility(View.GONE);
                    ll_empty.setVisibility(View.GONE);

                    return;
                }
                for (int i = 0; i < mSortHeadRoomMember.size(); i++) {
                    if (mSortHeadRoomMember.get(i).getBean().getShowName().contains(str)) { // 符合搜索条件的好友
                        mSearchRoomMember.add(mSortHeadRoomMember.get(i));
                    }
                }
                if (mSearchRoomMember.size()>0){
                    recy_search.setVisibility(View.VISIBLE);
                    ll_empty.setVisibility(View.GONE);
                }else {
                    recy_search.setVisibility(View.GONE);
                    ll_empty.setVisibility(View.VISIBLE);

                }
                membersHeadAdapter.notifyDataSetChanged();
            }
        });
    }

    private void initViews(String strHint) {
        LayoutInflater mInflater = LayoutInflater.from(mActivity);
        searchView = mInflater.inflate(R.layout.item_popup_search, null);
        ediSearch = searchView.findViewById(R.id.edi_search);
        ediSearch.setHint(strHint);
        ediSearch.setFocusable(true);
        ll_empty = searchView.findViewById(R.id.ll_empty);
        recy_search = searchView.findViewById(R.id.recy_search);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recy_search.setLayoutManager(manager);

        membersHeadAdapter = new GroupMembersHeadAdapter(mSearchRoomMember);
        recy_search.setAdapter(membersHeadAdapter);
        membersHeadAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                RoomMember roomMember  = mSearchRoomMember.get(position).getBean();
                dismissPopupWindow();
                listener.onSearchItemClick(roomMember);
            }
        });

        alphaView = searchView.findViewById(R.id.popup_window_v_alpha);
        tvCancle = searchView.findViewById(R.id.tvCanale);
        popupWindow = new PopupWindow(searchView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    public void showSearchBar() {
        getStatusBarHeight();
        moveHeight = topTitleView.getHeight();
        Animation translateAnimation = new TranslateAnimation(0, 0, 0,
                -moveHeight);
        translateAnimation.setDuration(300);
        fatherView.startAnimation(translateAnimation);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {
            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                //打开软键盘
                AppUtils.openKeyboard(mActivity);
                TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 0);
                fatherView.setAnimation(anim);
                topTitleView.setVisibility(View.GONE);
                topTitleView.setPadding(0, -moveHeight, 0, 0);

                popupWindow.showAtLocation(fatherView, Gravity.CLIP_VERTICAL,
                        0, statusBarHeight);
            }
        });
    }

    View.OnClickListener onClick = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch (v.getId()) {
                case R.id.popup_window_v_alpha:
                    dismissPopupWindow();
                    break;
                case R.id.tvCanale:
                    dismissPopupWindow();
                    break;
            }
        }
    };

   /* *//*判断键盘是否打开*//*
    private boolean isSoftShowing() {
        //获取当前屏幕内容的高度
        int screenHeight = mActivity.getWindow().getDecorView().getHeight();
        //获取View可见区域的bottom
        Rect rect = new Rect();
        mActivity.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight - rect.bottom != 0;
    }
*/
    private void dismissPopupWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            if (AppUtils.isSoftShowing(mActivity)){
                //隐藏软键盘
                AppUtils.openKeyboard(mActivity);
            }
            resetUI();
            popupWindow.dismiss();
        }
    }

    private void getStatusBarHeight() {
        Rect frame = new Rect();
        mActivity.getWindow().getDecorView()
                .getWindowVisibleDisplayFrame(frame);// 这里得到的是除了系统自带显示区域之外的所有区域，这里就是除了最上面的一条显示电量的状态栏之外的所有区域
        statusBarHeight = frame.top; // 这里便可以得到状态栏的高度，即最上面一条显示电量，信号等

    }

  /*  *//**
     * 展开隐藏键盘
     *//*
    private void openKeyboard() {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) mActivity
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 0);
    }*/
    private void resetUI() {
        topTitleView.setPadding(0, 0, 0, 0);
        topTitleView.setVisibility(View.VISIBLE);
        Animation translateAnimation = new TranslateAnimation(0, 0,
                -moveHeight, 0);
        translateAnimation.setDuration(300);
        fatherView.startAnimation(translateAnimation);
        translateAnimation.setAnimationListener(new Animation.AnimationListener() {

            @Override
            public void onAnimationStart(Animation arg0) {

            }

            @Override
            public void onAnimationRepeat(Animation arg0) {

            }

            @Override
            public void onAnimationEnd(Animation arg0) {
                TranslateAnimation anim = new TranslateAnimation(0, 0, 0, 0);
                fatherView.setAnimation(anim);
            }
        });
    }

    public interface onItemClickOListener{
        void onSearchItemClick(RoomMember roomMember);
    }
}
